'''Title  : GoogleQuote
   Version: 0.9
   Author : Glenn Y. Chen
   Summary: Check Stock Quote with Google Finance
   License: FreeBSD 
'''

import urllib    
import StringIO
import sys
from Tkinter import * #Gui library


    
class Application:
    def __init__(self, parent):
        frame = Frame(parent)
        frame.pack()
                
        self.myLabel = Label(root, text="Please enter one or more symbols")
        self.myLabel.pack()

        #self.myMessage = Message(root, text="myMessage")
        #self.myMessage.pack()

        self.myEntry = Entry(root)
        self.myEntry["background"] = "orange"
        
        self.myEntry.pack()

        self.myButton = Button(root, text="Check Price", command=self.getQuoteToMyMessageWidget)
        self.myButton["width"] = 250
        self.myButton.pack()

        self.myText = Text(root)
        self.myText.pack()
        

    def stream(self, contents):
        stream = StringIO.StringIO(contents)
        for line in stream:
	    if line.startswith('<span class="pr"'):
                start = line.find('>')+1
                end   = line.rfind('</sp')
                return line[start:end]
        print 'oops, need code change~quote not found'

    def getHtmlSource(self, symbol):   
        sock = urllib.urlopen("http://finance.google.com/finance?q="+symbol) 
        htmlSource = sock.read()
        sock.close()  
        return self.stream(htmlSource)

    def getTaiwanQuote(self, number):
        sock = urllib.urlopen("http://tw.stock.yahoo.com/q/q?s="+number)
        htmlSource = sock.read()
        sock.close()
        return self.streamTaiwan(htmlSource)

    def streamTaiwan(self, contents):
        stream = StringIO.StringIO(contents)
        for line in stream:
            targetLine =  '<td align="center" bgcolor="#FFFfff" nowrap>'
            if (line.lstrip()).startswith(targetLine):
                line = stream.readline()
                start = line.find('b>')+2
                end   = line.rfind('</b')
                return line[start:end]
        print 'oops, need code change~quote not found'

    def hexCheck(self, string):
        return string.encode("hex") > "39393939".encode("hex")

    def usage():
        print 'usage:'
        print 'python googlequote.py [symbol | ... ]'
        print 
        print '(you will be rich one day)'


    def getQuoteToMyMessageWidget(self):
        #self.myText.insert(END, "processing stock information")
        contents = self.myEntry.get()
        contents = contents.split()
        for symbol in contents:
            self.myText.insert(END, "\n")
            self.myText.insert(END, symbol.upper()+" ")
            self.myText.insert(END, self.getHtmlSource(symbol))
            self.myText.insert(END, "\n")


    '''def getInputFromTextWidget(self):
        contents = self.myText.get(1.0, END)
        return contents
    '''

if __name__ == "__main__":
    '''    if len(sys.argv) < 2:
       usage()

    for arg in sys.argv[1:]:
	if hexCheck(arg):
            print arg.upper()+' '+getHtmlSource(arg)	    
        else:
            print arg+' '+getTaiwanQuote(arg)
    '''

    root = Tk()
    app = Application(root)
    root.maxsize(200, 300)
    root.title("Google Quote")
    root.mainloop()


